<?php
/*
	分离uchome的 模板引擎
	说明：
	模板文件夹在 template 目录下， 默认是default文件夹。
	模板缓存在 data/tpl_cache目录下。
*/


$mtime = explode(' ',microtime());
$A_GLOBAL['timestamp'] = $mtime[1];//时间戳 ,生成模板和 更新模板的时候会用到
$A_GLOBAL['i'] = 0;
$A_GLOBAL['acanajax'] = 0;//是否使用ajax xml输出
$A_GLOBAL['block_search'] = $A_GLOBAL['block_replace'] = array();



//----模板引擎入口
	function Afun_template($name,$cache_path="",$type="") {
		Afun_file_mkdirm(Acan_tpl_cache_path);
		Afun_file_mkdirm(Acan_tpl_cache_patho);
		//检查$name中是否存在 '/' 
		if(!defined('Acan_app_path')){
			exit('请先定义 Acan_app_path!');
		}
		
		if(Afun_tpl_strexists($name,'public/')) {
			$tpl = Acan_path_tpl.'/'.$name;
		}elseif(Afun_tpl_strexists($name,'/')) {
			$tpl = Acan_path_tpl.'/'.Acan_app_path.$name;
		}else{
			$tpl = Acan_path_tpl."/".Acan_tpl_default."/".$name;
		}
		if(empty($cache_path)){
			$objfile = Acan_tpl_cache_path.str_replace('/','_',$tpl).'.php';
			if(!is_dir(Acan_tpl_cache_path)){
				Afun_file_mkdir(Acan_tpl_cache_path);
			}
		}else{
			$objfile = Acan_tpl_cache_patho.str_replace('/','_',$tpl).'.php';
			if(!is_dir(Acan_tpl_cache_patho)){
				echo Acan_tpl_cache_patho;
				echo Afun_file_mkdir(Acan_tpl_cache_patho);
			}
		}
		if(!file_exists($objfile)) {
			Afun_tpl_parse_template($tpl,$objfile,$type);
		}
		return $objfile;
	}

//判断字符串$haystack中是否存在字符$needle 返回第一次出现的位置   三个等号 判断绝对相等  uican 2009-12-03
	function Afun_tpl_strexists($haystack, $needle) {
		return !(strpos($haystack, $needle) === FALSE);
	}

//---生成模板缓存
function Afun_tpl_parse_template($tpl,$objfile,$type="") {
	global $A_GLOBAL;
	//$objfile	模板缓存文件路径
	//包含模板
	$A_GLOBAL['sub_tpls'] = array($tpl);

	//----模板文件路径
	 $tplfile = A_ROOT.$tpl.'.htm';
	
	//如果不存在则设为默认路径的模板
	if(!file_exists($tplfile)) {
		$tplfile = str_replace('/'.Acan_app_name.'/', '/public/', $tplfile);
	}
	$template = Afun_tpl_sreadfile($tplfile);
	if(empty($template)) {
		exit("模板文件 : $tplfile 不存在!");
	}

//	$template = preg_replace("/[\n\r\t]*\{Atemplate\s+(.+?)\}[\n\r\t]*/ies", "Afun_tpl_readtemplate('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{Atemplate\s+(.+?)\}[\n\r\t]*/ies", "Afun_tpl_readtemplate('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{block\/(\d+?)\}[\n\r\t]*/ie", "Afun_tpl_blocktags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{ad\/(.+?)\}[\n\r\t]*/ies", "Afun_tpl_adtags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{ad\s+([a-zA-Z0-9_\[\]]+)\/(.+?)\}[\n\r\t]*/ie", "Afun_tpl_adtags('\\2', '\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{avatar\((.+?)\)\}[\n\r\t]*/ie", "Afun_tpl_avatartags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{date\((.+?)\)\}[\n\r\t]*/ies", "Afun_tpl_datetags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\s*\}[\n\r\t]*/ies", "Afun_tpl_evaltags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{form\s+(.+?)\s*\}[\n\r\t]*/ies", "Afun_tpl_formtags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{html\s+(.+?)\s*\}[\n\r\t]*/ies", "Afun_tpl_htmltags('\\1')", $template);
//	$template = preg_replace("/[\n\r\t]*\{blockdata\/(\d+?)\}[\n\r\t]*/ie", "\$this->blockdatatags('\\1')", $template);

//	模板
	$template = preg_replace("/\<\!\-\-\{Atemplate\s+([a-z0-9_\/]+)\}\-\-\>/ies", "Afun_tpl_readtemplate('\\1')", $template);
//	处理子页面中的代码
	$template = preg_replace("/\<\!\-\-\{Atemplate\s+([a-z0-9_\/]+)\}\-\-\>/ies", "Afun_tpl_readtemplate('\\1')", $template);
//	解析模块调用
	$template = preg_replace("/\<\!\-\-\{block\/(.+?)\}\-\-\>/ie", "Afun_tpl_blocktags('\\1')", $template);
//	解析广告
	$template = preg_replace("/\<\!\-\-\{ad\s+(.+?)\s*\}\-\-\>/ies", "Afun_tpl_adtags('\\1')", $template);
//	头像处理
	$template = preg_replace("/\<\!\-\-\{avatar\((.+?)\)\}\-\-\>/ie", "Afun_tpl_avatartags('\\1')", $template);
//	时间处理
	$template = preg_replace("/\<\!\-\-\{date\s+(.+?)\s*\}\-\-\>/ies", "Afun_tpl_datetags('\\1')", $template);
//	PHP代码
	$template = preg_replace("/\<\!\-\-\{eval\s+(.+?)\s*\}\-\-\>/ies", "Afun_tpl_evaltags('\\1')", $template);
//	form处理
	$template = preg_replace("/\<\!\-\-\{form\s+(.+?)\s*\}\-\-\>/ies", "Afun_tpl_formtags('\\1')", $template);
//	html处理
	$template = preg_replace("/\<\!\-\-\{html\s+(.+?)\s*\}\-\-\>/ies", "Afun_tpl_htmltags('\\1')", $template);

	$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
	$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
	//开始处理
	//变量
	$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\-\>)?[a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*(\-\>)?[a-zA-Z0-9_\x7f-\xff]*)";
//	$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\-\>)?[a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
	//常量
	$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
	//$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\-\>\$\.]*)(\[[a-zA-Z0-9_\-\>\.\$\'\[\]\x7f-\xff]+\])*)";
	$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
	$template = preg_replace("/(\\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\.([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/s", "\\1['\\2']", $template);
	$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\-\>\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
	$template = preg_replace("/$var_regexp/es", "Afun_tpl_addquote('<?=\\1?>')", $template);
	$template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "Afun_tpl_addquote('<?=\\1?>')", $template);
	//逻辑
	$template = preg_replace("/\{elseif\s+(.+?)\}/ies", "Afun_tpl_stripvtags('<?php } elseif(\\1) { ?>','')", $template);
	$template = preg_replace("/\{else\}/is", "<?php } else { ?>", $template);
	//循环
	for($i = 0; $i < 6; $i++) {
		$template = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}(.+?)\{\/loop\}/ies", "Afun_tpl_stripvtags('<?php if(is_array(\\1) || is_object(\\1)) { foreach(\\1 as \\2) { ?>','\\3<?php } } ?>')", $template);
		$template = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}(.+?)\{\/loop\}/ies", "Afun_tpl_stripvtags('<?php if(is_array(\\1) || is_object(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<?php } } ?>')", $template);
		$template = preg_replace("/\{if\s+(.+?)\}(.+?)\{\/if\}/ies", "Afun_tpl_stripvtags('<?php if(\\1) { ?>','\\2<?php } ?>')", $template);
	}
	$template = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);
	
	//替换
	if(!empty($A_GLOBAL['block_search'])) {
		$template = str_replace($A_GLOBAL['block_search'], $A_GLOBAL['block_replace'], $template);
	}
	
	//换行
	$template = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);
	
	//附加处理
	$template = "<?php Afun_tpl_subtplcheck('".implode('|', $A_GLOBAL['sub_tpls'])."', '$A_GLOBAL[timestamp]', '$tpl', '$objfile', '$type');?>$template<?php Afun_ob_out('$type');?>";
	
	//write
	if(!file_put_contents($objfile, $template)) {
		exit("文件: $objfile 不能写入!");
	}
}

function Afun_tpl_addquote($var) {
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function Afun_tpl_striptagquotes($expr) {
	$expr = preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr);
	$expr = str_replace("\\\"", "\"", preg_replace("/\[\'([a-zA-Z0-9_\-\.\x7f-\xff]+)\'\]/s", "[\\1]", $expr));
	return $expr;
}

function Afun_tpl_evaltags($php) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--EVAL_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php ".Afun_tpl_stripvtags($php)." ?>";
	
	return $search;
}
function Afun_tpl_formtags($form) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--EVAL_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php echo Afunc_html()->form($form); ?>";
	
	return $search;
}
function Afun_tpl_htmltags($form) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--EVAL_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php echo Afunc_html()->$form; ?>";
	return $search;
}
function Afun_tpl_blocktags($parameter) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--BLOCK_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php block(\"$parameter\"); ?>";
	return $search;
}

function Afun_tpl_adtags($pagetype) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--AD_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php echo Afun_ad('$pagetype'); ?>";
	return $search;
}

function Afun_tpl_datetags($format) {
	global $A_GLOBAL;
	$A_GLOBAL['i']++;
	$search = "<!--EVAL_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php echo Afun_time_date($format); ?>";
	return $search;
}

function Afun_tpl_avatartags($parameter) {
	global $A_GLOBAL;

	$A_GLOBAL['i']++;
	$search = "<!--AVATAR_TAG_{$A_GLOBAL['i']}-->";
	$A_GLOBAL['block_search'][$A_GLOBAL['i']] = $search;
	$A_GLOBAL['block_replace'][$A_GLOBAL['i']] = "<?php echo avatar($parameter); ?>";
	return $search;
}

function Afun_tpl_stripvtags($expr, $statement='') {
	$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
	$statement = str_replace("\\\"", "\"", $statement);
	return $expr.$statement;
}

function Afun_tpl_readtemplate($name) {
	global $A_GLOBAL;
	//检查$name中是否存在 '/' 
	if(!defined('Acan_app_path')){
		exit('请先定义 Acan_app_path!');
	}
	if(Afun_tpl_strexists($name,'public/')) {
		$tpl = Acan_path_tpl.'/'.$name;
	}elseif(Afun_tpl_strexists($name,'/')) {
		$tpl = Acan_path_tpl.'/'.Acan_app_path.$name;
	} else {
		//Acan_tpl_default 为选择的模板
		$tpl = Acan_path_tpl."/".Acan_tpl_default."/".$name;
	}
//	$tpl = Afun_tpl_strexists($name,'/') ? Acan_path_tpl.'/app/'.$name : Acan_path_tpl."/".Acan_tpl_default."/".$name;
	$tplfile = A_ROOT.$tpl.'.htm';
	
	$A_GLOBAL['sub_tpls'][] = $tpl;
	
	if(!file_exists($tplfile)) {
		echo $tplfile;
		$tplfile = str_replace('/'.Acan_app_name.'/', '/public/', $tplfile);
	}
	$content = Afun_tpl_sreadfile($tplfile);
	return $content;
}

//获取文件内容
function Afun_tpl_sreadfile($filename) {
	$content = '';
	if(function_exists('file_get_contents')) {
		@$content = file_get_contents($filename);
	} else {
		if(@$fp = fopen($filename, 'r')) {
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}

/**
 *  //子模板更新检查  uican 2009-12-04  该函数还未了解   需研究
 *
 * @param string $subfiles 模板路径
 * @param int $mktime 时间  （未知，需了解 uican）
 * @param string $tpl  当前页面模板
 */
function Afun_tpl_subtplcheck($subfiles, $mktime, $tpl, $objfile,$type="") {

	if(defined('Acan_tpl_auto_refresh') && (Acan_tpl_auto_refresh == 1 || mt_rand(1, Acan_tpl_auto_refresh) == 1)) {
		$subfiles = explode('|', $subfiles);
		foreach ($subfiles as $subfile) {
			$tplfile = A_ROOT.$subfile.'.htm';
			if(!file_exists($tplfile)) {
				$tplfile = str_replace('/'.Acan_app_name.'/', '/public/', $tplfile);
			}
			@$submktime = filemtime($tplfile);
			if($submktime > $mktime) {
				//include_once(A_ROOT.'./source/function_template.php');
				Afun_tpl_parse_template($tpl,$objfile,$type);
				break;
			}
		}
	}
}

function Afun_ob_out($type='') {
	global $A_GLOBAL;

	$content = ob_get_contents();

	$preg_searchs = $preg_replaces = $str_searchs = $str_replaces = array();
	if(defined('Acan_tpl_allowrewrite') && Acan_tpl_allowrewrite == 1) {
		$preg_searchs[] = "/\<a href\=\"index.php\"/i";
		$preg_searchs[] = "/\<a href\=\"index.php\?a=([0-9a-zA-Z_,*-\/\x7f-\xff]+)\"/ie";
		$preg_searchs[] = "/\<a href\=\"\/index.php\?a=([0-9a-zA-Z_,*-\/\x7f-\xff]+)\"/ie";

		$preg_replaces[] = '<a href="/'.A_ROOT.'"';
		$preg_replaces[] = 'Afun_rewrite_url(\'\',\'\\1\')';
		$preg_replaces[] = 'Afun_rewrite_url(\'\',\'\\1\')';
	}
	/*	??未知??
	if($A_CONFIG['linkguide']) {
		$preg_searchs[] = "/\<a href\=\"http\:\/\/(.+?)\"/ie";
		$preg_replaces[] = 'iframe_url(\'\\1\')';
	}
	*/
	if($A_GLOBAL['acanajax']) {
		$preg_searchs[] = "/([\x01-\x09\x0b-\x0c\x0e-\x1f])+/";
		$preg_replaces[] = ' ';

		$str_searchs[] = ']]>';
		$str_replaces[] = ']]&gt;';
	}

	if($preg_searchs) {
		$content = preg_replace($preg_searchs, $preg_replaces, $content);
	}
	if($str_searchs) {
		$content = trim(str_replace($str_searchs, $str_replaces, $content));
	}

	Afun_tpl_obclean();
	Afun_html_cache($content);
	if($A_GLOBAL['acanajax']) {
		Afun_tpl_xml_out($content);
	}elseif($type=='json') {
		Afun_tpl_json_out($content);
	}elseif($type=='html') {
		return $content;
	}else{
		if(defined('Acan_tpl_charset')) {
			@header('Content-Type: text/html; charset='.Acan_tpl_charset);
		}
		echo $content;
	}
}
//rewrite链接
function rewrite_url($pre, $para,$url) {
	$para = str_replace(array('&','='), array('/','/'), $para);
	return '<a href="/'.$pre.$para.'"';
}
function Afun_rewrite_url($pre, $para) {
	$para = str_replace(array('&','='), array('/','/'), $para);
	return '<a href="/'.$pre.$para.'"';
}

function Afun_tpl_obclean() {
	ob_end_clean();
	if (defined('Acan_tpl_gzipcompress') && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}
function Afun_tpl_xml_out($content) {
	@header("Expires: -1");
	@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
	@header("Pragma: no-cache");
	@header("Content-type: application/xml; charset=".Acan_tpl_charset);
	echo '<'."?xml version=\"1.0\" encoding=\"".Acan_tpl_charset."\"?>\n";
	echo "<root><![CDATA[".trim($content)."]]></root>";
	exit();
}
function Afun_tpl_json_out($content) {
	@header("Expires: -1");
	@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
	@header("Pragma: no-cache");
	//输出JSON字符串
	@header("Content-type: application/json; charset=".Acan_tpl_charset);
	echo Ajson_encode($data);
	exit();
}


?>